﻿package net.pezzato.graphics {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.Stage;
	import flash.net.URLRequest;
	import flash.display.Loader;
	/**
	 * ...
	 * @author Alessandro Pezzato
	 */
	public class Photo extends Sprite {
		public static const THUMBNAIL:Number = 1;
		public static const NORMAL:Number = 2;
		public static const T_SIZE:Number = 100;
		private static var nSize_s:Number = 0;
		private var url_:String;
		private var img_:Loader;
		private var size_:Number;
		private var maxSize_:Number;
		public function Photo(url:String, size:Number) {
			size_ = size;
			if (nSize_s == 0) {
				throw new Error("errorPhotoNormalSizeNotConfigured");
			}
			load(url);
		}
		public static function get N_SIZE():Number {
			return nSize_s;
		}
		private function load(url:String):void {
			img_ = new Loader();
			img_.contentLoaderInfo.addEventListener(Event.COMPLETE, onPhotoLoaded);
			var request:URLRequest = new URLRequest(url);
			img_.load(request);
		}
		private function onPhotoLoaded(event:Event):void {
			switch (size_) {
				case THUMBNAIL: {
					rescaleTo(T_SIZE);
					break;
				}
				case NORMAL: {
					rescaleTo(nSize_s);
					break;
				}
			}
			addChild(img_);
			drawBg();
			center();
		}
		public static function adaptNormalSizeToStage(s:Stage):void {
			/*
			 * Adatta la dimensione "normale" della foto in base al
			 * lato piu' corto dello stage.
			 * Es.: se lo stage e' 640x480, la foto sara' avra al massimo
			 * altezza e larghezza di 480*0.8 = 384;
			 */
			if (s.stageWidth > s.stageHeight) {
				nSize_s = s.stageHeight * 0.8;
			} else {
				nSize_s = s.stageWidth * 0.8;
			}
		}
		private function rescaleTo(max:Number):void {
			maxSize_ = max;
			trace(maxSize_);
			if (img_.width > img_.height) {
				var originalWidth:Number = img_.width;
				img_.width = max;
				img_.height *= originalWidth / max;
			} else {
				var originalHeight:Number = img_.height;
				img_.height = max;
				img_.width *= originalHeight / max;
			}
		}
		private function drawBg():void {
			trace(maxSize_);
			graphics.beginFill(0x000000, 0.1);
			graphics.lineStyle(1, 0x000000, 0.5, true);
			graphics.drawRect(-1, -1, maxSize_ + 1, maxSize_ + 1);
		}
		private function center():void {
			img_.x = (maxSize_ - img_.width) / 2;
			img_.y = (maxSize_ - img_.height) / 2;
		}
	}
}